var loading = (function(window, document) {
  /**
   * @type {HTMLDivElement}
   */
  var $el = null;

  /**
   * @type {HTMLElement}
   */
  var $bar = null;

  /**
   * @type {HTMLElement}
   */
  var $text = null;

  var fragment = document.createDocumentFragment();

  function checkEl() {
    if ($el == null) {
      throw new Error('call `loading.init` first');
    }
  }

  function init() {
    $el = document.getElementById('loading.ad115') || null;
    checkEl();
    $bar = $el.querySelector('.progress-bar .progress');
    $text = $bar.querySelector('.progress-text');

    $text.innerText = '0.00%';
  }

  function show() {
    checkEl();

    if (document.body.contains($el)) {
      return;
    }

    fragment.removeChild($el);
    document.body.appendChild($el);
  }

  function hide() {
    checkEl();

    document.body.removeChild($el);
    fragment.appendChild($el);
  }

  function setProgress(percent) {
    checkEl();

    var width = (+percent).toFixed(2) + '%';
    $bar.style.width = width;
    $text.innerText = width;
  }

  function reset() {
    checkEl();

    if (fragment.contains($el)) {
      fragment.removeChild($el);
      document.body.appendChild($el);
    }

    $bar.style.width = '0%';
    $text.innerText = '0%';
  }

  const ins = {
    init,
    show,
    hide,
    setProgress,
    reset,
  };

  window.loading = ins;

  return ins;
})(window, document);

loading.init();
